import { request } from '@/config/api'
import { useAuthStore } from '@/stores/auth'

export interface StudyAction {
  chapterId: string
  lessonId?: string
  actionType: 'video_watch' | 'material_click' | 'exercise_complete'
  details?: string
}

export interface StudentProgress {
  id: number
  userId: number
  courseId: string
  chapterId: string
  lessonId?: string
  actionType: string
  timestamp: string
  details?: string
}

class ProgressService {
  /**
   * 记录学习行为
   * @param action 学习行为数据
   */
  async recordStudyAction(action: StudyAction): Promise<void> {
    try {
      // 检查用户是否为学生角色，只对学生记录行为
      const authStore = useAuthStore()
      if (!authStore.isAuthenticated || !authStore.isStudent) {
        console.log('非学生用户，跳过行为记录')
        return
      }
      // 检查是否已经记录过相同的行为（防止重复记录）
      const existingRecords = await this.getProgressByUser()
      
      // 对于视频观看，检查是否在短时间内重复记录
      if (action.actionType === 'video_watch') {
        const recentVideoWatch = existingRecords.find(record => 
          record.chapterId === action.chapterId &&
          record.lessonId === action.lessonId &&
          record.actionType === 'video_watch' &&
          this.isRecentAction(record.timestamp, 5) // 5分钟内不重复记录
        )
        
        if (recentVideoWatch) {
          console.log('视频观看记录已存在，跳过重复记录')
          return
        }
      }
      
      // 对于资料点击，允许重复记录但要限制频率
      if (action.actionType === 'material_click') {
        const recentMaterialClick = existingRecords.find(record => 
          record.chapterId === action.chapterId &&
          record.lessonId === action.lessonId &&
          record.actionType === 'material_click' &&
          record.details === action.details &&
          this.isRecentAction(record.timestamp, 1) // 1分钟内不重复记录相同资料
        )
        
        if (recentMaterialClick) {
          console.log('资料点击记录过于频繁，跳过重复记录')
          return
        }
      }
      
      // 记录学习行为
      await request('/student-progress', {
        method: 'POST',
        body: JSON.stringify({
          courseId: 'vue-course', // 固定课程ID
          chapterId: action.chapterId,
          lessonId: action.lessonId || null,
          actionType: action.actionType,
          details: action.details || null
        })
      })
      
      console.log('学习行为记录成功:', action)
    } catch (error) {
      console.error('记录学习行为失败:', error)
      // 不抛出错误，避免影响用户体验
    }
  }
  
  /**
   * 获取当前用户的学习进度
   */
  async getProgressByUser(): Promise<StudentProgress[]> {
    try {
      const response = await request<StudentProgress[]>('/student-progress/user/current')
      return response || []
    } catch (error) {
      console.error('获取学习进度失败:', error)
      return []
    }
  }
  
  /**
   * 获取指定用户的学习进度
   * @param userId 用户ID
   */
  async getProgressByUserId(userId: number): Promise<StudentProgress[]> {
    try {
      const response = await request<StudentProgress[]>(`/student-progress/user/${userId}`)
      return response || []
    } catch (error) {
      console.error('获取用户学习进度失败:', error)
      return []
    }
  }
  
  /**
   * 获取所有学习进度（管理员功能）
   */
  async getAllProgress(): Promise<StudentProgress[]> {
    try {
      const response = await request<StudentProgress[]>('/student-progress')
      return response || []
    } catch (error) {
      console.error('获取所有学习进度失败:', error)
      return []
    }
  }
  
  /**
   * 获取聚合进度数据
   */
  async getAggregatedProgress(): Promise<any[]> {
    try {
      const response = await request<any[]>('/student-progress/aggregated')
      return response || []
    } catch (error) {
      console.error('获取聚合进度数据失败:', error)
      return []
    }
  }
  
  /**
   * 检查是否是最近的行为
   * @param timestamp 时间戳
   * @param minutes 分钟数
   */
  private isRecentAction(timestamp: string, minutes: number): boolean {
    const actionTime = new Date(timestamp).getTime()
    const now = new Date().getTime()
    const diffMinutes = (now - actionTime) / (1000 * 60)
    return diffMinutes < minutes
  }
  
  /**
   * 记录视频观看
   * @param chapterId 章节ID
   * @param lessonId 课时ID
   * @param videoTitle 视频标题
   */
  async recordVideoWatch(chapterId: string, lessonId: string, videoTitle?: string): Promise<void> {
    await this.recordStudyAction({
      chapterId,
      lessonId,
      actionType: 'video_watch',
      details: videoTitle
    })
  }
  
  /**
   * 记录资料点击
   * @param chapterId 章节ID
   * @param materialName 资料名称
   * @param materialUrl 资料链接
   */
  async recordMaterialClick(chapterId: string, materialName: string, materialUrl?: string): Promise<void> {
    await this.recordStudyAction({
      chapterId,
      lessonId: materialName, // 使用资料名称作为lessonId
      actionType: 'material_click',
      details: materialUrl || materialName
    })
  }
  
  /**
   * 记录练习完成
   * @param chapterId 章节ID
   * @param exerciseName 练习名称
   * @param score 得分
   */
  async recordExerciseComplete(chapterId: string, exerciseName: string, score?: number): Promise<void> {
    await this.recordStudyAction({
      chapterId,
      lessonId: exerciseName,
      actionType: 'exercise_complete',
      details: score ? `得分: ${score}` : undefined
    })
  }
  
  /**
   * 批量记录学习行为
   * @param actions 学习行为数组
   */
  async recordBatchActions(actions: StudyAction[]): Promise<void> {
    for (const action of actions) {
      await this.recordStudyAction(action)
      // 添加小延迟避免请求过于频繁
      await new Promise(resolve => setTimeout(resolve, 100))
    }
  }
  
  /**
   * 获取章节学习统计
   * @param chapterId 章节ID
   */
  async getChapterStats(chapterId: string): Promise<{
    videoWatches: number
    materialClicks: number
    exerciseCompletes: number
    lastStudyTime: string | null
  }> {
    try {
      const progress = await this.getProgressByUser()
      const chapterProgress = progress.filter(p => p.chapterId === chapterId)
      
      return {
        videoWatches: chapterProgress.filter(p => p.actionType === 'video_watch').length,
        materialClicks: chapterProgress.filter(p => p.actionType === 'material_click').length,
        exerciseCompletes: chapterProgress.filter(p => p.actionType === 'exercise_complete').length,
        lastStudyTime: chapterProgress.length > 0 
          ? chapterProgress.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())[0].timestamp
          : null
      }
    } catch (error) {
      console.error('获取章节统计失败:', error)
      return {
        videoWatches: 0,
        materialClicks: 0,
        exerciseCompletes: 0,
        lastStudyTime: null
      }
    }
  }
}

// 导出单例实例
export const progressService = new ProgressService()
export default progressService